package com.finley.flowabledemo.service;


import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LeaveProcessService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    // 启动请假流程
    public String startLeaveProcess(String applicant, int days, String reason) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("username", applicant);
        variables.put("days", days);
        variables.put("reason", reason);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveProcess", variables);
        return processInstance.getId();
    }

    // 审批任务（支持通过/拒绝）
    public void approveTask(String taskId, String approver, boolean approved, String comment) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        // 先认领任务（如果是候选人）
        taskService.claim(taskId, approver);
        Map<String, Object> variables = new HashMap<>();
        variables.put("approved", approved);
        variables.put("comment", comment);
        taskService.complete(taskId, variables);
    }

    // 查询当前用户的待办任务（包括候选任务）
    public List<Task> get待办任务(String userId) {
        return taskService.createTaskQuery()
                .taskAssignee(userId)
                .or()
                .taskCandidateUser(userId)
                .endOr()
                .orderByTaskCreateTime().desc()
                .list();
    }
}
